from server import *
from threading import Thread
import os
import re

test_html = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Refresh" content="5">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<h1>我的第一个标题</h1>
<p>我的第一个段落。</p>
</body>
</html>
'''

def getHtmlDefault(handle, request_msg):
	print("request_msg: ", request_msg)
	return test_html

class WebServerHandle(baseServerHandler):

	def handle(self):
		self.clientsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.data = self.clientsock.recv(2048)
		if len(self.data) > 0:
			self.recvDataDispose(self.data)

	def recvDataDispose(self, data):
		# print(self.data.decode("utf-8"))
		r = re.search(r"GET /(.+?) ", data.decode("utf-8"))
		rspHead	 = "HTTP/1.1 200 OK\r\nServer: foreverServer\r\n\r\n"
		if r == None:
			rspBody = self.args["getHtml"](self, r)
		else:
			rspBody = self.args["getHtml"](self, r.group(1))
		self.sendData((rspHead + rspBody).encode("utf-8"))

class WebServer(TCPServer):
	def __init__(self, host="", port=4001, getHtml=getHtmlDefault, HandleArgs={}):
		HandleArgs["getHtml"] = getHtml
		TCPServer.__init__(self, host=host, port=port, Handler=WebServerHandle, HandleArgs=HandleArgs)

if __name__=="__main__":		# 测试程序
	web = WebServer()
	while True:
		input("")